﻿using System.Collections.Generic;

namespace DM4Script
{
    public partial class ScriptParse
    {
        /// ifexpr ::= 'if' expression 'then' expression 'else' expression
        private Prototypes.ExprAst ParseIfExpr(Queue<string> taskExists)
        {
            GetNextToken();  // Получаем if.

            if (_curTok != '(')
                return Error("Expected '(' in prototype"); 
            
            GetNextToken(); 

            // условие.
            Prototypes.ExprAst cond = ParseExpression(taskExists);
            if (cond == null) return null;

            if (_curTok != ')')
                return Error("Expected ')' or command in prototype");

            GetNextToken();
            Prototypes.ExprAst thenIf = ParsesCommands();
            if (thenIf == null) return null;

            Prototypes.ExprAst elseIf = null;
            
            if (_curTok == (char)Token.ElseIf)
            {
                elseIf = ParseIfExpr(taskExists);
                if (elseIf == null) return null;
            }
            else if (_curTok == (char)Token.Else)
            {
                GetNextToken();
                elseIf = ParsesCommands();
                if (elseIf == null) return null;
            }

            if (_curTok != (char)Token.RunTask && _curTok != (char)Token.Eof)
                return Error("Expected 'ON' or EOF in prototype");

            return new Prototypes.IfExprAst(cond, thenIf, elseIf);
        }
    }
}
